<template>
  <div>
    <a-card class="card"  :bordered="false">
      <task-form ref="task" :showSubmit="false" />
    </a-card>
    
    <!-- table -->
    <a-card>

      <a-button type="primary" @click="showModal">
        新增
      </a-button>
      <a-modal  :visible="visible" title="新增学生表信息" ok-text="确认" cancel-text="取消" @ok="handleOk" @cancel="handleCancel">

        <a-form
            @submit="handleSubmit"
            :model="form"
            class="form"
            :rules="rules"
            ref="taskForm"
        >

          <a-row class="form-row" :gutter="16">
            <a-col :lg="12" :md="12" :sm="12" >
              <a-form-item label="姓名" name="stuName">
                <a-input placeholder="请输入姓名" v-model:value="form.stuName" />
              </a-form-item>
            </a-col>
            <a-col :lg="12" :md="12" :sm="12" >
              <a-form-item label="学号" name="stuId">
                <a-input placeholder="请输入学号" v-model:value="form.stuId" />
              </a-form-item>
            </a-col>
          </a-row>


          <a-row class="form-row" :gutter="16" >
            <a-col :lg="12" :md="12" :sm="12" >
              <a-form-item label="班级" name="stuClass" >
                <a-input placeholder="请输入班级" v-model:value="form.stuClass" />
              </a-form-item>
            </a-col>
            <a-col :lg="12" :md="12" :sm="12" >
              <a-form-item label="性别" name="stuGender">
                <a-select placeholder="请性别" v-model:value="form.stuGender">
                  <a-select-option value="男">男</a-select-option>
                  <a-select-option value="女">女</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-modal>






      <a-table
        :columns="columns"
        :dataSource="data"
        :pagination="false"
        :loading="memberLoading"
      >
        <template >
          <template >{{ text }}</template>
        </template>
        <template #operation="{ record }" >
          <span >
            <a @click="toggle(record.key)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="是否要删除此行？" @confirm="remove(record.key)">
              <a>删除</a>
            </a-popconfirm>
          </span>
        </template>
      </a-table>


      <a-pagination
          show-quick-jumper
          :default-current="1"
          :total="50"
          show-less-items
          @change="onChange"
      />
    </a-card>
    
    <!-- fixed footer toolbar -->
    <footer-tool-bar :collapsed="collapse">
      <span class="popover-wrapper">
        <a-popover
          title="表单校验信息"
          overlayClassName="antd-pro-pages-forms-style-errorPopover"
          trigger="click"
          :getPopupContainer="trigger => trigger.parentNode"
        >
          <template #content>
            <li
              v-for="item in errors"
              :key="item.key"
              @click="scrollToField(item.key)"
              class="antd-pro-pages-forms-style-errorListItem"
            >
              <CloseCircleOutlined class="antd-pro-pages-forms-style-errorIcon" />
              <div class="">{{ item.message }}</div>
              <div class="antd-pro-pages-forms-style-errorField">{{ item.fieldLabel }}</div>
            </li>
          </template>
          <span class="antd-pro-pages-forms-style-errorIcon" v-if="errors.length > 0">
            <ExclamationOutlined />{{ errors.length }}
          </span>
        </a-popover>
      </span>
      <a-button type="primary" @click="validate" :loading="loading">提交</a-button>
    </footer-tool-bar>
  </div>
</template>

<script>
  import { mapState } from 'vuex';
  import {Form, Card, Button, Input, DatePicker, Select, TimePicker, Popover, Table, Popconfirm, Divider, message, Modal, Pagination} from 'ant-design-vue';
  import { ExclamationOutlined, CloseCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import RepositoryForm from './components/ResponsitoryForm.vue';
  import TaskForm from './components/TaskForm.vue';
  import FooterToolBar from './components/FooterToolbar.vue';
  const FormItem = Form.Item;
  const { Option } = Select;
  const { RangePicker } = DatePicker;

  const fieldLabels = {
    stuName: '姓名',
    stuId: '学号',
    stuClass: '班级',
    stuGender: '性别',

  };



  export default {
    name: 'AdvancedForm',
    components: {
      FooterToolBar,
      RepositoryForm,
      TaskForm,
      APagination:Pagination,
      AModal: Modal,
      ATable: Table,
      ADivider: Divider,
      AForm: Form,
      ACard: Card,
      AButton: Button,
      APopover: Popover,
      APopconfirm: Popconfirm,
      ARangePicker: RangePicker,
      ATimePicker: TimePicker,
      AInput: Input,
      AFormItem: FormItem,
      ASelect: Select,
      ASelectOption: Option,
      ExclamationOutlined,
      CloseCircleOutlined,
      PlusOutlined
    },
    computed: {
      ...mapState({
        collapse: state => state.collapse
      })
    },
    data () {
      return {
        loading: false,
        memberLoading: false,
        // collapse: false,
        key:'',
        visible: false,
        editable: false,
        form: {
          stuName: '',
          stuId: '',
          stuClass: '',
          stuGender: '',
        },
        formItemLayout: {
          labelCol: {
            xs: { span: 24 },
            sm: { span: 8 },
          },
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 16 },
          }
        },
        rules: {
          stuName: [{ required: true, message: '请输入姓名', whitespace: true}],
          stuId: [{ required: true, message: '请输入学号', whitespace: true}],
          stuClass: [{ required: true, message: '请选择班级'}],
          stuGender: [{ required: true, message: '请选择性别'}],
        },
        // table
        columns: [
          {
            title: '姓名',
            dataIndex: 'stuName',
            key: 'stuName',
            width: '17%',
            slots: { customRender: 'stuName' }
          },
          {
            title: '学号',
            dataIndex: 'stuId',
            key: 'stuId',
            width: '17%',
            slots: { customRender: 'stuId' }
          },
          {
            title: '班级',
            dataIndex: 'stuClass',
            key: 'stuClass',
            width: '17%',
            slots: { customRender: 'stuClass' }
          },
          {
            title: '性别',
            dataIndex: 'stuGender',
            key: 'stuGender',
            width: '12%',
            slots: { customRender: 'stuGender' }
          },
          {
            title: '操作',
            key: 'action',
            slots: { customRender: 'operation' }
          }
        ],
        data: [
          {
            key: '1',
            stuName: '小明',
            stuId: '001',
            editable: false,
            stuClass: '软件工程1班',
            stuGender:'男'
          },
          {
            key: '2',
            stuName: '李莉',
            stuId: '002',
            editable: false,
            stuClass: '软件工程2班',
            stuGender:'女'
          },
          {
            key: '3',
            stuName: '王小帅',
            stuId: '003',
            editable: false,
            stuClass: '软件工程2班',
            stuGender:'男'
          }
        ],

        errors: []
      }
    },

    methods: {
      onChange(pageNumber) {
        console.log('Page: ', pageNumber);
      },

      showModal() {
        this.visible = true;
        this.form = {};
      },
      handleOk() {
        if (!this.form.stuName || !this.form.stuId || !this.form.stuClass || !this.form.stuGender) {
          this.memberLoading = false;
          this.$message.error('请填写完整成员信息。');
          return
        }
        if(this.editable) {
          const target = this.data.find(item => item.key === this.key);
          target.stuName = this.form.stuName;
          target.stuId = this.form.stuId;
          target.stuClass = this.form.stuClass;
          target.stuGender = this.form.stuGender;
        }
        else {
          const length = this.data.length;
          const stuName = this.form.stuName;
          const stuId = this.form.stuId;
          const stuClass = this.form.stuClass;
          const stuGender = this.form.stuGender;
          this.data.push({
            key: length === 0 ? '1' : (parseInt(this.data[length - 1].key) + 1).toString(),
            stuName: stuName,
            stuId: stuId,
            stuClass: stuClass,
            stuGender: stuGender,
            editable: false,
          })
        }
        this.editable = false;
        this.visible = false;

      },
      handleCancel(key){
        this.visible = false;
        this.editable = false;
      },
      handleSubmit (e) {
        e.preventDefault()
      },
      remove (key) {
        const newData = this.data.filter(item => item.key !== key);
        this.data = newData
      },
      toggle (key) {
        this.visible = true;
        this.editable = true;
        this.key = key;
        const target = this.data.find(item => item.key === key);
        this.form.stuName = target.stuName
        this.form.stuId = target.stuId
        this.form.stuClass = target.stuClass
        this.form.stuGender = target.stuGender
      },
      getRowByKey (key, newData) {
        const data = this.data;
        return (newData || data).find(item => item.key === key)
      },
      cancel (key) {
        this.visible = false;
        const target = this.data.find(item => item.key === key);
        Object.keys(target).forEach(key => { target[key] = target._originalData[key] });
        target._originalData = undefined
      },
      handleChange (key) {
        const target = this.data.find(item => item.key === key);
      },

      // 最终全页面提交
      validate () {
        let isCorrect = false;
        let isTaskCorrect = false;
        const { $refs: { repository, task }, $notification } = this;
        const repositoryForm = new Promise((resolve, reject) => {
          repository.form.validateFields((err, values) => {
            if (err) {
              reject(err);
              isCorrect = false;
              return
            }
            isCorrect = true;
            resolve(values);
          })
        });
        const taskForm = new Promise((resolve, reject) => {
          task.form.validateFields((err, values) => {
            if (err) {
              reject(err);
              isTaskCorrect = false;
              return
            }
            isTaskCorrect = true;
            resolve(values)
          })
        });
        if (isCorrect && isTaskCorrect) {
          console.log('接收到的表单数据:', {...repository.form.getFieldsValue(), ...task.form.getFieldsValue()});
          message.success('提交成功');
        }
        // clean this.errors
        this.errors = [];
        Promise.all([repositoryForm, taskForm]).then(values => {
          $notification['error']({
            message: 'Received values of form:',
            description: JSON.stringify(values)
          });
        }).catch(() => {
          const errors = Object.assign({}, repository.form.getFieldsError(), task.form.getFieldsError());
          const tmp = { ...errors };
          this.errorList(tmp);
        });
      },
      errorList (errors) {
        if (!errors || errors.length === 0) {
          return
        }
        this.errors = Object.keys(errors)
          .filter(key => errors[key])
          .map(key => ({
            key: key,
            message: errors[key][0],
            fieldLabel: fieldLabels[key]
          }))
      },
      scrollToField (fieldKey) {
        const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
        if (labelNode) {
          labelNode.scrollIntoView(true)
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .card{
    margin-bottom: 24px;
  }
  .popover-wrapper {
    /deep/ .antd-pro-pages-forms-style-errorPopover .ant-popover-inner-content {
      min-width: 256px;
      max-height: 290px;
      padding: 0;
      overflow: auto;
    }
  }
  .antd-pro-pages-forms-style-errorIcon {
    user-select: none;
    margin-right: 24px;
    color: #f5222d;
    cursor: pointer;
    i {
      margin-right: 4px;
    }
  }
  .antd-pro-pages-forms-style-errorListItem {
    padding: 8px 16px;
    list-style: none;
    border-bottom: 1px solid #e8e8e8;
    cursor: pointer;
    transition: all .3s;
    
    &:hover {
      background: #e6f7ff;
    }
    .antd-pro-pages-forms-style-errorIcon {
      float: left;
      margin-top: 4px;
      margin-right: 12px;
      padding-bottom: 22px;
      color: #f5222d;
    }
    .antd-pro-pages-forms-style-errorField {
      margin-top: 2px;
      color: rgba(0,0,0,.45);
      font-size: 12px;
    }
  }
</style>
